import os, time, sys, urllib, urllib2, re
import xbmcplugin,xbmcgui,xbmc,xbmcaddon

__settings__ = xbmcaddon.Addon(id='plugin.video.gs')
set_lang = int(__settings__.getSetting( "lang" ))
set_ps = int(__settings__.getSetting( "pref_server" ))
set_aplay = __settings__.getSetting( "aplay" )
if set_aplay=="true":
	set_aplay = 1
if set_aplay=="false":
	set_aplay = 0
set_apq = int(__settings__.getSetting( "apq" ))
#Variables
UAS = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 ( .NET CLR 3.5.30729; .NET4.0C)'
video_dl = []
def remove_html_tags(string):
	string = re.sub('<.+?>', '', string)
	return string
	
def get_title(html):
	regex = '<h.+?><a href=.+?">(.+?)</a></h.+?></div>'
	titles = re.compile(regex).findall(html)
	if len(titles) > 0:
		return remove_html_tags(titles[0])
	else:
		return "ERROR"

def get_thumbnail(html):
	regex = '<div style="padding-bottom:10px;"><a href=.+?><img class="news-img-border".+?src="(.+?)" alt=".+?" title=".+?" /></a></div>'
	regex = '<div style="padding-bottom:10px;"><a href=.+?><img .+?src="(.+?)".+?</div>'
	images = re.compile(regex).findall(html)
	if len(images) > 0:
		return images[0]
	else:
		regex2 = '<a href=".+?"><img src="(.+?)".+?/>'
		images2 = re.compile(regex2).findall(html)
		if len(images2) > 0:
			return images2[0]
		else:
			return "ERROR"

def get_screenies_from_vids(url,html):
	#regex it
	regex = '<a href="#" onclick="openimagepopup.+?;return false;"><img src="(.+?)".+?</a>'
	images = re.compile(regex).findall(html)
	screenshots = []
	if len(images) > 0:
		name = "View Screenshot Slideshow"
		name = name + " (" + str(len(images)) + ")"
		filename = xbmc.translatePath(os.path.join('special://profile/addon_data/plugin.video.gs/', 'cache'))
		thumbnail = images[0]
		addScreenshot(name, url, thumbnail)
	else:
		print "No Images"

def get_screenshots(url):
	UAS = 'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10 ( .NET CLR 3.5.30729; .NET4.0C)'
	req = urllib2.Request(url)
	req.add_header('User-Agent', UAS)
	response = urllib2.urlopen(req)
	html=response.read()
	response.close()
	html = html.replace("\n", "")
	html = html.replace("\r", "")

	# Cache Folder Preparation
	folder = xbmc.translatePath(os.path.join('special://profile/addon_data/plugin.video.gs/', 'cache'))
	if os.path.isdir(folder)==False:
		os.makedirs(folder)

	for the_file in os.listdir(folder):
		file_path = xbmc.translatePath(os.path.join(folder, the_file))
		if os.path.isfile(file_path):
			os.unlink(file_path)

	#regex it
	regex = '<a href="#" onclick="openimagepopup.+?;return false;"><img src="(.+?)".+?</a>'
	images = re.compile(regex).findall(html)
	screenshots = []
	if len(images) > 0:
		total = len(images)
		for image in images:
			screenshots.append(image)
	else:
		print "Error"
		return "ERROR"
	
	return screenshots
		
def Generate_Slideshow(screenshots):
	global pDialog
	name = "JESUS"
	pDialog = xbmcgui.DialogProgress()
	dia_title = "Getting Image(s)"
	dia_l1 = name
	ret = pDialog.create(dia_title, dia_l1)
	current_item = 0
	total = len(screenshots)
	for image in screenshots:
		current_item = current_item + 1

		name = image.replace('http://images.gamersyde.com/thumb_', '')	
		thumbnail = image
		screenshot = image.replace('gamersyde.com/thumb_', 'gamersyde.com/')
		filename = xbmc.translatePath(os.path.join('special://profile/addon_data/plugin.video.gs/', 'cache', name))
		print "Filename: " + str(filename)
		print "URL: " + str(screenshot) 
		img_download(filename, screenshot, current_item, total)
		
	return
	
def img_download(fname,url,current_item,total):
	from urllib2 import Request, urlopen, URLError, HTTPError
	req = Request(url)
	try:
		global pDialog
		percent = (float(current_item) / float(total)) * float(100)
		name = url.replace('http://images.gamersyde.com/', '')
		pDialog.update(int(percent), name)
		
		f = urlopen(req)
		local_file = open(fname, "wb")
		local_file.write(f.read())
		local_file.close()
		


	except HTTPError, e:
		print "HTTP Error:",e.code , url
	except URLError, e:
		print "URL Error:",e.reason , url
	return

def get_news(html):
	regex = '<div style="padding-bottom:10px;">.+?</div>(.+?)</div></div>'
	news = re.compile(regex).findall(html)
	if len(news) > 0:
		return news[0]
	else:
		regex2 = '<p>(.+?)</div.+?/div>'
		news2 = re.compile(regex2).findall(html)
		if len(news2) > 0:
			return news2[0]
		else:
			return "No News"
			
def get_link_to_videopage(html):
    regex = '<h.+?><a href="(.+?)".+?</h.+?>'
    links = re.compile(regex).findall(html)
    if len(links) > 0:
        return links[0]
    else:
        return "ERROR"

def get_video_dl(title,image,url):
	global video_dl
	req = urllib2.Request(url)
	req.add_header('User-Agent', UAS)
	response = urllib2.urlopen(req)
	html=response.read()
	response.close()
	image = 'http://www.gamersyde.com/' + image
	
	print "IMAGE: " + image

	regex = '<li><A HREF=(.+?)>.+?</a> (.+?)</li>'
	videos = re.compile(regex).findall(html)
	for link,name in videos:
		print "Name: " + name
		print "Video Link: " + link
		video_dl.append(link)
		fname = title + " (" + name + ")"
		addLink(fname,link,image)
		
def get_video_stream_urls(html):
	global set_lang
	video_array = []
	if set_lang==0:
		regex  = '<div class="video-content-top" style="background-image:url\((.+?)\).+?<div class="video-content-firstline.+?>(.+?)</div>.+?<div class="video-content-view">.+?a href="(.+?)">Stream the video</a>'
	if set_lang==1:
		regex  = '<div class="video-content-top" style="background-image:url\((.+?)\).+?<div class="video-content-firstline.+?>(.+?)</div>.+?<div class="video-content-view">.+?a href="(.+?)">Visionner en streaming</a>'

	videos = re.compile(regex).findall(html)
	for image,title,link in videos:
		append_line = "<title>" + title + "</title><image>" + image + '</image><link>http://www.gamersyde.com/' + link + "</link>"
		video_array.append(append_line)
		print "SU Title: " + title
		print "SU Image: " + image
		print "SU Link: " + link
	return video_array

def get_video_streams(video_array):
	regex = '<title>(.+?)</title><image>(.+?)</image><link>(.+?)</link>'
	for item in video_array:
		video_item = re.compile(regex).findall(item)
		for title,image,link in video_item:
			print "GETTING VIDEO DATA FOR: " + link
			get_video_dl(title,image,link)
			cur_url = link
	
	global video_dl
	global set_aplay
	if set_aplay==1:
		np = xbmc.getCondVisibility('Player.HasMedia')
		if np!=1:
			global set_apq
			video_link = play_video("http://www.gamersyde.com/" + video_dl[set_apq])
			cp_vf = xbmc.getInfoLabel("Player.Filenameandpath").split("/")[-1]
			np_vf = video_link.split("/")[-1]
			if np_vf!=cp_vf:
				xbmc.executebuiltin("XBMC.PlayMedia(" + video_link + ")")
		if np==1:
			global set_apq
			cp_vf = xbmc.getInfoLabel("Player.Filenameandpath").split("/")[-1]
			#print "CURRENTLY PLAYING: " + cp_vf
			video_link = play_video("http://www.gamersyde.com/" + video_dl[set_apq])
			np_vf = video_link.split("/")[-1]
			#print "TO BE PLAYED? : " + np_vf
			if np_vf!=cp_vf:
				xbmc.executebuiltin("XBMC.PlayMedia(" + video_link + ")")

def play_video(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', UAS)
	response = urllib2.urlopen(req)
	html=response.read()
	response.close()
	html = html.replace("\n", "")
	html = html.replace("\r", "")

	global set_ps
	if set_ps==0:
		regex1 = '<li><a href=.+?dldedibox.gamersyde.com(.+?)>'
		regex1b = 'http://dldedibox.gamersyde.com/'
		regex2 = '<li><a href=.+?dlovh.gamersyde.com(.+?)>'
		regex2b = 'http://dlovh.gamersyde.com/'
	if set_ps==1:
		regex1 = '<li><a href=.+?dlovh.gamersyde.com(.+?)>'
		regex1b = 'http://dlovh.gamersyde.com/'
		regex2 = '<li><a href=.+?dldedibox.gamersyde.com(.+?)>'
		regex2b = 'http://dldedibox.gamersyde.com/'

	regex = regex1
	video_files = re.compile(regex).findall(html)
	for videolink in video_files:
		final_link = regex1b + videolink
		
	if len(video_files) < 1:
		regex = regex2
		video_files = re.compile(regex).findall(html)
		for videolink in video_files:
			final_link = regex2b + videolink

	if len(video_files) < 1:
		return "ERROR"
	else:
		return final_link

def index_request(url):
	req = urllib2.Request(url)
	req.add_header('User-Agent', UAS)
	response = urllib2.urlopen(req)
	link=response.read()
	response.close()
	link = link.replace("\r", "")
	link = link.replace("\n", "")
	return link

def addLink(name,url,iconimage):
	name = remove_html_tags(name)
	mode = 2
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	liz.setProperty("IsPlayable","true")
	liz.setProperty("Fanart_image", iconimage)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
	return ok

def addScreenshot(name,url,iconimage):
	name = remove_html_tags(name)
	mode = 4
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="image", infoLabels={ "Title": name } )
	liz.setProperty("Fanart_image", iconimage)
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
	return ok
	
	
def addDir(name,url,mode,iconimage):
	name = remove_html_tags(name)
	u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	ok=True
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok
	

